package cn.itcast.service.impl;

import cn.itcast.dao.CourierDao;
import cn.itcast.domain.Courier;
import cn.itcast.service.CourierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.ArrayList;

@Service
public class CourierServiceImpl implements CourierService {

    @Autowired
    private CourierDao courierDao;

    /**
     * 添加查询
     * @param courier
     */
    @Override
    public void save(Courier courier) {
        courierDao.save(courier);
    }

    /**
     * 分页查询
     * @param page
     * @param rows
     * @return
     */
    @Override
    public Page<Courier> pageQuery(int page, int rows) {
        PageRequest pageRequest = new PageRequest(page - 1, rows);
        return courierDao.findAll(pageRequest);
    }

    /**
     * 删除操作
     * @param ids
     */
    @Override
    @Transactional
    public void delete(int ids) {
            courierDao.delete(ids);

    }

    /**
     * 还原操作
     * @param ids
     */
    @Override
    @Transactional
    public void init(int ids) {
        courierDao.init(ids);
    }

    /**
     * 动态分页条件查询
     * @param courier
     * @param page
     * @param rows
     * @return
     */
    @Override
    @Transactional
    public  Page<Courier> pageQuery(Courier courier, int page, int rows) {


        Specification<Courier> specification = new Specification<Courier>() {//查询条件构造
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) {
                ArrayList<Predicate> list = new ArrayList<>();
                if (courier.getCourierNum()!=null&&!"".equals(courier.getCourierNum())){
                list.add(cb.like(root.get("courierNum"),courier.getCourierNum()));
            }
                if (courier.getCompany()!=null&&!"".equals(courier.getCompany())){
                list.add(cb.like(root.get("company"),courier.getCompany()));
            }
                if (courier.getType()!=null&&!"".equals(courier.getType())){
                list.add(cb.like(root.get("type"),courier.getType()));
            }
                return cb.and(list.toArray(new Predicate[0]));
        }
        };
        PageRequest pageRequest =  PageRequest.of(page - 1, rows);//分页信息
        Page<Courier> couriers = courierDao.findAll(specification, pageRequest);
        System.out.println("hahaha");
        return couriers;
    }
}
